package com.zxy.ider.ehome;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewPropertyAnimator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.http.HttpHandler;
import com.zxy.ider.ehome.R;
import com.zxy.ider.ehome.View.DownLoadDialog;
import com.zxy.ider.ehome.View.TitleTextView;
import com.zxy.ider.ehome.View.TvProgressBar;
import com.zxy.ider.ehome.adapter.DownloadListAdapter;
import com.zxy.ider.ehome.adapter.FileAdapter;
import com.zxy.ider.ehome.adapter.FilePathAdapter;
import com.zxy.ider.ehome.bean.DownloadInfo;
import com.zxy.ider.ehome.bean.MyFile;
import com.zxy.ider.ehome.service.DownloadService;
import com.zxy.ider.ehome.util.DownloadManager;
import com.zxy.ider.ehome.util.DownloadRequestCallBack;
import com.zxy.ider.ehome.util.NetUtil;
import com.zxy.ider.ehome.util.TvUtil;

import org.xutils.common.Callback;
import org.xutils.common.task.PriorityExecutor;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

public class WebActivity extends Activity {
    private WebView webView;
    private boolean isShow = false;
    private RelativeLayout rightR;
    private View view_bg;
    private GridView downloadinfoGrid;
    private DownloadManager dManager;
    private DownloadListAdapter downLoadadapter=null;
    private Button allstart,allcancel,alldelete;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        webView = (WebView) findViewById(R.id.my_web);
        webView.getSettings().setJavaScriptEnabled(true);
        view_bg = findViewById(R.id.view_bg);
        rightR = (RelativeLayout) findViewById(R.id.downManager);
        allstart = (Button) findViewById(R.id.alldownload);
        allcancel = (Button) findViewById(R.id.allcancelback);
        alldelete = (Button) findViewById(R.id.alldelete);
        alldelete.setOnClickListener(onclicker);
        allcancel.setOnClickListener(onclicker);
        allstart.setOnClickListener(onclicker);
        webView.setWebViewClient(new WebViewClient(){
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        webView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onReceivedTitle(WebView view, String title) {
                // TODO Auto-generated method stub
                super.onReceivedTitle(view, title);
            }
        });
        webView.setDownloadListener(new MyDownloadStart());
        //webView.loadUrl(" file:///android_asset/test.html");
        webView.loadUrl("http://mp.encm.com.cn/down");
        dManager = DownloadService.getDownloadManager(Appcontext.getAppContext());

        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.REFRESH);
        registerReceiver(refreshreceiver,filter);
        initdata();
    }

    View.OnClickListener onclicker = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
          if(view.getId()==R.id.allcancelback){
              new Thread(new Runnable() {
                  @Override
                  public void run() {
                      try {
                          dManager.stopAllDownload();
                      } catch (DbException e) {
                          e.printStackTrace();
                      }
                  }
              }).start();

          }
          if(view.getId()==R.id.alldownload){
              List<DownloadInfo> downloadInfoList  = dManager.getDownloadInfoList();
              for (int i = 0;i<downloadInfoList.size();i++)
              {DownloadInfo downloadInfo = downloadInfoList.get(i);
                  if(downloadInfo.getState().equals(HttpHandler.State.CANCELLED.toString())){
                      try {
                          dManager.resumeDownload(downloadInfo,
                                  new DownloadRequestCallBack(Appcontext.getAppContext(),
                                  dManager, downloadInfo.getDid()));
                      } catch (DbException e) {
                          e.printStackTrace();
                      }
                  }
              }
          }
            if(view.getId()==R.id.alldelete){
                try {
                    dManager.deleteHistory();
                    downLoadadapter = null;
                    downloadinfoGrid.setAdapter(null);
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    private void initdata() {
        if(downLoadadapter==null) {
            downLoadadapter = new DownloadListAdapter(Appcontext.getAppContext());
            downloadinfoGrid = (GridView) findViewById(R.id.downloadinfo);
            downloadinfoGrid.setAdapter(downLoadadapter);
        }else{
            downLoadadapter.notifyDataSetChanged();
        }
    }


    BroadcastReceiver refreshreceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        downLoadadapter.notifyDataSetChanged();
    }
};

    @Override
    protected void onDestroy() {
        try{
            unregisterReceiver(refreshreceiver);
        }catch (Exception e){
            e.printStackTrace();
        }
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if ((keyCode==KeyEvent.KEYCODE_BACK)&&webView.canGoBack()) {
            if(!webView.getUrl().equals("http://mp.encm.com.cn/down")) {
                webView.goBack();
                return true;
            }else{
                return super.onKeyDown(keyCode, event);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    EditText patht;
    List<MyFile> data=null;
    FilePathAdapter adapter=null;
    DownLoadDialog DownLoadDialog=null;
    String savePath = Constant.SAVEPATH;
    class MyDownloadStart implements DownloadListener {
        @Override
        public void onDownloadStart(final String url, String userAgent,
                                    String contentDisposition, String mimetype, final long contentLength) {
            savePath = getResources().getString(R.string.rootpath);
            DownLoadDialog =  new DownLoadDialog(WebActivity.this,R.layout.add_dialog,R.style.MyDialog);
            patht = (EditText) DownLoadDialog.findViewById(R.id.filepath);
            final GridView pathgrid = (GridView) DownLoadDialog.findViewById(R.id.filepath_Grid);
            data = getFileDir(Environment
                    .getExternalStorageDirectory().getPath());
            adapter = new FilePathAdapter(data);
            pathgrid.setAdapter(adapter);
            final long FileSize = contentLength;
            pathgrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    MyFile  file =  data.get(i);
                    Log.i("zxy", "onDownloadStart:url= "+file.getAbsolutePath()+file.getFileName());
                    if(file.exists()&&file.isDirectory()){
                        data.clear();
                        data=null;
                        data =  getFileDir(file.getAbsolutePath()+"/"+file.getFileName());
                        adapter = new FilePathAdapter(data);
                        pathgrid.setAdapter(adapter);
                        savePath = file.getAbsolutePath()+"/"+file.getFileName()+"/";
                        patht.setText("保存到:"+file.getAbsolutePath()+"/"+file.getFileName()+"/");
                    }
                }
            });
            DownLoadDialog.findViewById(R.id.download).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.i("zxy", "onClick: downloading");
//                    Drawable dra = WebActivity.this.getResources().getDrawable(R.mipmap.file_type_video);
//                    Bitmap bit = ((BitmapDrawable)dra).getBitmap();
                    new Thread(){
                        @Override
                        public void run() {
                            String did = System.currentTimeMillis()+"";
                            dManager.addNewDownload(did,url,URLDecoder.decode(NetUtil.getNameFromUrl(url)),FileSize,savePath+ URLDecoder.decode(NetUtil.getNameFromUrl(url))+"mp4",true,true
                                    ,new DownloadRequestCallBack(WebActivity.this,dManager,url)
                            );
                        }
                    }.start();
                    refreshData();
                    showRightManager();
                    DownLoadDialog.cancel();
                    DownLoadDialog.dismiss();

                }
            });
            DownLoadDialog.findViewById(R.id.cancelback).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    DownLoadDialog.cancel();
                    DownLoadDialog.dismiss();
                }
            });
            DownLoadDialog.show();

        }

    }


    public List<MyFile> getFileDir(String path){
        List<MyFile> files= null;
        File fileparent = new File(path);
        if(fileparent.exists()){
            files = new ArrayList<MyFile>();
            MyFile myfie = null;
            if(fileparent.isDirectory()){
                File[] filesRoot =fileparent.listFiles();
                for (int i = 0 ;i <  filesRoot.length;i++){
                    File file =filesRoot[i];
                    if(!file.exists()){
                        return null;
                    }
                    if(file.isDirectory()){
                        Log.i("zzz", "getFileDir: file.getName()=="+file.getName());
                        myfie = new MyFile(path,getFiletyPe(R.mipmap.file_type_file) ,
                                file.getName(),null,true,"dirs");
                        files.add(myfie);
                    }

                }
                return files;
            }
            return null;
        }
        return null;
    }
    private Drawable getFiletyPe(int id ){
        return Appcontext.getAppContext().getDrawable(id);
    }


    public void managerClick(View view){
        if(TvUtil.isFastDoubleClick()){
            return;
        }
        showRightManager();
    }


    public void showRightManager(){
        if(isShow) {
            isShow=false;
            ObjectAnimator animator = ObjectAnimator.ofFloat(view_bg, "alpha", 0.5f, 0.0f);
            animator.setDuration(300);
            animator.start();
            pullDownTopDialog(rightR, getResources().getDimension(R.dimen.px2500));
        }else{
            isShow=true;
            ObjectAnimator animator = ObjectAnimator.ofFloat(view_bg, "alpha", 0.0f, 0.5f);
            animator.setDuration(300);
            animator.start();
            pullDownTopDialog(rightR, getResources().getDimension(R.dimen.px1400));
        }
    }
    Handler handler = new Handler();
    public void refreshData(){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                initdata();
            }
        }, 1000);
    }


    public void refreshadapter(){
        handler.postDelayed(refresh, 1000);
    }


    Thread refresh = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i =0;i<downloadinfoGrid.getChildCount();i++) {
                ((DownloadListAdapter.ViewHolder) downloadinfoGrid.getChildAt(i).getTag()).refresh();
            }
           // refreshData();
        }
    });

    public void pullDownTopDialog(View viewRight, Float y) {

            ViewPropertyAnimator topDialogAnimator = viewRight.animate();
            viewRight.bringToFront();
            topDialogAnimator.x(y);
            topDialogAnimator.y(0);
            topDialogAnimator.setDuration(300);
            topDialogAnimator.start();

    }
}
